package com.library.Language.controller;

import com.library.Language.model.Language;
import com.library.Language.model.LanguageExample;
import com.library.Language.service.LanguageService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class LanguageController {
    
    private LanguageService languageService;

    //通过构造器注入service
    @Autowired
    public LanguageController(LanguageService languageService) {
        this.languageService = languageService;
    }

    //查询数据
    @GetMapping("/language")
    @ResponseBody
    public List<Language> list() {
        //1 构造查询条件
        //1.1 创建查询条件类
        LanguageExample example = new LanguageExample();
        //1.2 创建条件构造器
        LanguageExample.Criteria criteria = example.createCriteria();
        //1.3 通过criteria设置条件
        //...
        
        //2 根据条件查询，如果没有查询条件，传入一个空的example即可
        List<Language> list = languageService.selectByExample(example);
        
        //3 返回结果
        return list;
    }

    //添加数据
    @PostMapping("/language")
    @ResponseBody
    public Language add(@RequestBody Language language) {
        //1 准备数据，例如设置language主键等
        //...
        language.setId((int) (System.currentTimeMillis() % 1000000000));
        
        //2 插入数据
        languageService.insertSelective(language);
        
        //3 把新添加的数据返回给调用者
        return language;
    }

    //修改数据
    @PutMapping("/language")
    @ResponseBody
    public Language update(@RequestBody Language language) {
        //1 准备数据，例如设置language的修改时间等
        //...
        
        //2 更新数据
        languageService.updateByPrimaryKeySelective(language);
        
        //3 把新修改的数据返回给调用者
        return languageService.selectByPrimaryKey(language.getId());
    }

    //删除数据
    @DeleteMapping("/language/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        //1 根据主键删除数据
        languageService.deleteByPrimaryKey(id);
        
        //2 返回一个状态码给调用者
        return "200";
    }
}